package demo.realm;

import demo.entity.User;
import demo.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.Set;


public class MyRealm extends AuthorizingRealm {

    @Resource
    private UserService userService;


    /**
     * 为当前登陆成功的用户授予权限和角色，已经登陆成功了
     *
     * @param principals 登陆实体
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(
            PrincipalCollection principals) {
        //获取用户名
        String username = (String) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        Set<String> roles = userService.getRoles(username);
        System.out.println("开始赋值Role======================");
        for (String role : roles) {
            System.out.println("role   "+role);
        }
        System.out.println("结束赋值Role======================");
        authorizationInfo.setRoles(roles);
        Set<String> permissions = userService.getPermissions(username);
        System.out.println("开始赋值Permissions*********************");
        for (String permission : permissions) {
            System.out.println("permission   "+permission);
        }
        System.out.println("开始赋值Permissions*********************");
        authorizationInfo.setStringPermissions(permissions);
        return authorizationInfo;
    }

    /**
     * 验证当前登录的用户，获取认证信息
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken token) throws AuthenticationException {
        // 获取用户名
        String username = (String) token.getPrincipal();
        User user = userService.getByUsername(username);
        if (user != null) {
            AuthenticationInfo authInfo = new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), this.getName());
            return authInfo;
        } else {
            return null;
        }

    }

}
